package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;

/**
 * @author ：wanghao
 * @date ：Created in 2020/12/6
 * @description ：菜单管理服务层接口实现类
 * @version: 1.0
 */
@Service
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;
    @Autowired
    private JedisPool jedisPool;

    // 条件查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Menu> page = menuDao.selectByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Menu> findOneAll() {
        return menuDao.findOneAll();
    }

    @Override
    public void add(Menu menu) {
        Integer parentMenuId = menu.getParentMenuId();
        if (parentMenuId == null){
            menu.setLevel(1);
            Integer oneCount = menuDao.findOneCount();
            menu.setPriority(oneCount+1);
            menu.setPath(menu.getPriority()+1+"");
        }else{
            menu.setLevel(2);
            Integer twoCount = menuDao.findTwoCount(menu.getParentMenuId());
            menu.setPriority(twoCount+1);
            String path = "/"+menuDao.findPathByParentMenuId(menu.getParentMenuId())+"-"+menu.getPriority();
            menu.setPath(path);
        }
        menuDao.add(menu);
        if (menu.getIcon() != null && menu.getIcon().length() > 0){
            // 将图片名称保存到Redis
            savePic2Redis(menu.getIcon());
        }
    }

    @Override
    public Menu findById(Integer id) {
        return menuDao.findById(id);
    }

    @Override
    public void edit(Menu menu) {
        menuDao.updateById(menu);
        if (menu.getIcon() != null && menu.getIcon().length() > 0){
            savePic2Redis(menu.getIcon());
        }
    }

    @Override
    public void deleteById(Integer id) {
        // 查询改菜单项是否有二级菜单
        Integer count = menuDao.findCountByParentMenuId(id);
        if (count > 0){
            throw new RuntimeException("当前菜单有二级菜单关联，不能删除");
        }
        menuDao.deleteById(id);
    }

    @Override
    public List<Menu> findAll() {
        return menuDao.findAll();
    }

    private void savePic2Redis(String pic){
        Jedis jedis = jedisPool.getResource();
        jedis.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,pic);
        jedis.close();
    }

}
